﻿using System;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Text;
using Eagleshoes.PackingBarcode.Properties;

namespace Eagleshoes.PackingBarcode.Stock
{
    /// <summary>
    /// 库存查询窗口
    /// </summary>
    public partial class StockBarcodeQueryForm : Form
    {
        private readonly Scanner scanner = new Scanner();

        public StockBarcodeQueryForm()
        {
            InitializeComponent();
        }

        private void StockQueryForm_Load(object sender, EventArgs e)
        {
            scanner.DecodeEvent +=
                scanner_OnDecodeEvent;
            scanner.Start();
        }

        private void scanner_OnDecodeEvent(object s, DecodeEventArgs ev)
        {
            scanner.Stop();
            BeginInvoke((Action<string>) delegate(string barcode)
                {
                    BarcodeTextBox.Text = barcode;
                    scan(barcode);
                }, ev.Barcode.Trim('\0', '\t', '\n', '\r'));
        }


        private void scan(string code)
        {
            
            CartonService.GoodsInventory gi=null;
            try
            {
                gi = Program.CartonClient.GetGoodsInventoryByBarcode(code);
            }
            catch
            {
                Win32.sndPlaySound(Resources.通讯错误, Win32.SND_ASYNC | Win32.SND_MEMORY);
                BarcodeTextBox.Text = "请扫描货品条码";
                GoodsTextbox.Text = string.Empty;
                return;
            }
            if(gi==null)
            {
                BarcodeTextBox.Text = "请扫描货品条码";
                GoodsTextbox.Text = string.Empty;
            }
            else
            {
                Win32.sndPlaySound(Resources.叮, Win32.SND_ASYNC | Win32.SND_MEMORY);
              
                GoodsTextbox.Text = string.Format("货品编码:{0}\n货品名称:{1}\n单位:{2}\n账面库存:{3}\n实际库存:{4}", gi.GoodsCode, gi.GoodsName, gi.Unit, gi.Quantities, gi.StockQuantities);
            }
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void StockQueryForm_KeyUp(object sender, KeyEventArgs e)
        {
           if(e.KeyCode==Keys.Escape)
           {
               Close();
           }
        }

        private void StockQueryForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            scanner.DecodeEvent -= scanner_OnDecodeEvent;
            scanner.Stop();
        }

    }
}